<script src="{{ asset('admin/layui/layui.js') }}"></script>
<script>
    var ele = 'LAY-form';
    return_code = 0;
    var Common = function () {

        var initTable = function ( cols, where, doneCallBack ) {
            var table = layui.table;
            var ele = "#LAY-form";
            var url = "get_list";
            return table.render({
                elem: ele
                , url: url
                , method: 'get'
                , cellMinWidth: 80 //全局定义常规单元格的最小宽度，layui 2.2.1 新增
                , cols: cols
                , page: !0
                ,limit: 15
                ,limits: [1, 10, 15, 20]
                ,where: where
                ,even: false //开启隔行背景
                ,text: {
                    none: '暂无相关数据', //默认：无数据。注：该属性为 layui 2.2.5 开始新增
                }
                ,autoSort: false //禁用前端自动排序。注意：该参数为 layui 2.4.4 新增
                ,request: {
                    pageName: 'page',
                    limitName: 'perPage',
                }
                ,parseData: function(res){ //res 即为原始返回的数据
                    if(res.data.show_type == 1){
                        return {
                            "code": res.code, //解析接口状态
                            "count": "", //解析数据长度
                            "data": res.data.data //解析数据列表
                        };
                    }
                    return {
                        "code": res.code, //解析接口状态
                        "count": res.data.total, //解析数据长度
                        "data": res.data.data //解析数据列表
                    };
                }
                ,done: function (res, curr, count) {
                    if (typeof(doneCallBack) === "function") {
                        doneCallBack(res);
                    }
                }
            });
        };

        var addTable = function (title, modalUrl, postUrl, width = "600px", height = "400px", type = 2, btns = ["提交", "取消"]) {
            layer.open({
                type: type,
                title: title,
                content: modalUrl,
                maxmin: true,
                area: [width, height],
                btn: btns,
                yes: function(index, layero) {
                    var iframeWindow = window['layui-layer-iframe'+ index]
                        ,submitID = 'LAY-add-forms'
                        ,submit = layero.find('iframe').contents().find('#'+ submitID);

                    iframeWindow.layui.form.on('submit('+submitID+')', function(data){
                        layui.$.ajax({
                            type:"post",
                            url:postUrl,
                            headers:{
                                'X-CSRF-TOKEN': layui.$('meta[name="csrf-token"]').attr('content')
                            },
                            data:data.field ,
                            error:function(){
                                Common.systemReturn('系统错误!');
                            },
                            success:function(data){
                                if(data.code == return_code){
                                    Common.successReturn(data,index);
                                }else{
                                    Common.errorReturn(data)
                                }
                            }
                        });

                    });
                    submit.trigger('click');//模拟点击
                    submit.attr('disabled', false);
                }
            })
        };

        /**
         *
         * @param type 模态框类型
         * @param title 模态框标题
         * @param modalUrl 模态框Url
         * @param posrUrl 提交Url
         * @param width 模态框宽度
         * @param height
         */
        var editTable = function (type, title, modalUrl, postUrl, width, height) {
            layer.open({
                type: type,
                title: title,
                content: modalUrl,
                maxmin: true,
                area: [width, height],
                btn: ["提交", "取消"],
                yes: function(index, layero) {
                    var iframeWindow = window['layui-layer-iframe'+ index]
                        ,submitID = 'LAY-edit-forms'
                        ,submit = layero.find('iframe').contents().find('#'+ submitID);
                    iframeWindow.layui.form.on('submit('+submitID+')', function(data){
                        data.field;
                        layui.$.ajax({
                            type:"post",
                            url:postUrl,
                            data:data.field ,
                            headers:{
                                'X-CSRF-TOKEN': layui.$('meta[name="csrf-token"]').attr('content')
                            },
                            error:function(){
                                Common.systemReturn('系统错误!');
                            },
                            success:function(data){
                                if(data.code == 0){
                                    Common.successReturn(data,index);
                                }else{
                                    Common.errorReturn(data)
                                }
                            }
                        });

                    });
                    submit.trigger('click');//模拟点击
                    submit.attr('disabled', false);
                }
            })
        }

        var editCols = function (postUrl, obj) {
            var value = obj.value //得到修改后的值
                ,data = obj.data //得到所在行所有键值
                ,field = obj.field; //得到字段

            layui.$.ajax({
                type:"post",
                url:postUrl,
                data:data ,
                headers:{
                    'X-CSRF-TOKEN': layui.$('meta[name="csrf-token"]').attr('content')
                },
                error:function(){
                    Common.systemReturn('系统错误!');
                },
                success:function(data){
                    if(data.code == 0){
                        Common.successReturn(data);
                    }else{
                        Common.errorReturn(data);
                    }
                }
            });
        }

        var deleteTable = function (postUrl ,e) {
            layer.confirm("真的删除该数据么", function(t) {
                layui.$.ajax({
                    type:"delete",
                    url:postUrl,
                    data: {id: e.data.id},
                    headers:{
                        'X-CSRF-TOKEN': layui.$('meta[name="csrf-token"]').attr('content')
                    },
                    error:function(){
                        Common.systemReturn('系统错误!');
                    },
                    success:function(data){
                        if(data.code == 0){
                            e.del() //页面 删除行
                            Common.successReturn(data);
                        }else{
                            Common.errorReturn(data);
                        }
                    }
                });
                layer.close(t)
            })
        };

        var batchDeleteTable = function (postUrl ,e) {
            var checkStatus = layui.table.checkStatus(ele)
                ,checkData = checkStatus.data; //得到选中的数据
            if(checkData.length == 0){
                return layer.msg('请选择数据', {
                    icon: 2
                    ,time: 2000
                });
            }

            layer.confirm('确定删除选中数据吗？', function(index) {
                var ids = []
                layui.$.each(checkData,function(index,value){
                    ids.push(value.id)
                });

                //执行 Ajax 后重载
                layui.$.ajax({
                    type:"delete",
                    url:postUrl,
                    headers:{
                        'X-CSRF-TOKEN': layui.$('meta[name="csrf-token"]').attr('content')
                    },
                    data:{id: ids},
                    error:function(){
                        Common.systemReturn('系统错误!');
                    },
                    success:function(data){
                        if(data.code == 0){
                            Common.successReturn(data)
                        }else{
                            Common.errorReturn(data)
                        }
                    }
                });
            });
        };

        /**
         * 查询
         * @param data
         * @param type
         */
        var search = function (data,type) {
            if(type == 2){
                data.field = '';
            }
            var field = data.field;
            //执行重载
            layui.table.reload(ele, {
                where: field,
                page:{curr:1}
            });
        }

        /**
         * 排序
         * @param data
         */
        var sort = function (data) {
            layui.table.reload(ele, {
                initSort: data //记录初始排序，如果不设的话，将无法标记表头的排序状态。
                ,where: { //请求参数（注意：这里面的参数可任意定义，并非下面固定的格式）
                    field: data.field //排序字段
                    ,order: data.type //排序方式
                }
            });
        }

        var setStatus = function (postUrl) {
            layui.$.ajax({
                type:"post",
                url:postUrl,
                headers:{
                    'X-CSRF-TOKEN': layui.$('meta[name="csrf-token"]').attr('content')
                },
                data: '' ,
                error:function(){
                    Common.systemReturn('系统错误');
                },
                success:function(data){
                    if(data.code == 0){
                        Common.successReturn(data)
                    }else{
                        Common.errorReturn(data)
                    }
                }
            });
        }

        var upload = function (eleId, postUrl, layUpload, beforeEleId,exts, done, error, accept) {
            var $ = layui.$;
            layUpload.render({
                elem: eleId //绑定元素
                , url: postUrl //上传接口
                , accept: accept === undefined ? 'file' : accept
                , exts: exts === undefined ? 'jpg|png|gif|bmp|jpeg' : exts
                ,headers:{
                    'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
                }
                ,before: function(obj){
                    //预读本地文件示例，不支持ie8
                    obj.preview(function(index, file, result){
                        if(exts == 'jpg|png|gif|bmp|jpeg'){
                            $(beforeEleId).attr('src', result); //图片链接（base64）
                        }

                    });
                }
                , done: function (res) {
                    if(res.code != 0){
                        //演示失败状态，并实现重传
                        var demoText = $('#upload-Text');
                        demoText.html('<span style="color: #FF5722;">上传失败</span> <a class="layui-btn layui-btn-mini demo-reload">重试</a>');
                        demoText.find('.demo-reload').on('click', function(){
                            uploadInst.upload();
                        });
                    }else{
                        //上传成功
                        $('#upload-Text').remove()
                        $(this.item).prev("div").children("input").eq(0).val(res.data.file_path)
                        $(this.item).prev("div").children("input").eq(1).val(res.data.file_id)
                        $(this.item).prev("div").children("input").eq(2).val(res.data.file_name)
                    }
                }
                , error: function () {
                    //请求异常回调
                    //演示失败状态，并实现重传
                    var demoText = $('##upload-Text');
                    demoText.html('<span style="color: #FF5722;">上传失败</span> <a class="layui-btn layui-btn-mini demo-reload">重试</a>');
                    demoText.find('.demo-reload').on('click', function(){
                        uploadInst.upload();
                    });
                    if (typeof (error) === 'function') {
                        error()
                    }
                }
            });
        };

        var openFrame = function (url, title, width, height) {
            width = width === undefined ? '900px' : width;
            height = height === undefined ? '500px' : height;
            return top.layer.open({
                area: [width, height],
                type: 2,
                title: title,
                content: url //这里content是一个URL，如果你不想让iframe出现滚动条，你还可以content: ['http://sentsin.com', 'no']
            });
        };

        //返回
        var successReturn = function (data, index) {
            layer.msg(data.message, {
                icon: 1
                ,time: 2000
            },function () {
                layui.table.reload('LAY-form'); //数据刷新
                layer.close(index); //关闭弹层
            });
        }

        var errorReturn = function (data) {
            layer.msg(data.message, {
                icon: 2
                ,time: 2000
            },function () {

            });
        }

        var systemReturn = function (data) {
            layer.msg(data, {
                icon: 3
                ,time: 2000
            },function () {

            });
        }

        return {
            //初始化表格
            initTable: function ( cols, where, doneCallBack) {
                return initTable( cols, where, doneCallBack);
            },
            addTable: function (title, modalUrl, postUrl, width, height, type, btns) {
                return addTable(title, modalUrl, postUrl, width, height, type, btns);
            },
            editTable: function (type, title, modalUrl, postUrl, width, height) {
                return editTable(type, title, modalUrl, postUrl, width, height);
            },
            deleteTable: function (postUrl, e) {
                return deleteTable(postUrl, e);
            },
            batchDeleteTable: function (postUrl, e) {
                return batchDeleteTable(postUrl, e);
            },
            editCols: function (postUrl, obj) {
                return editCols(postUrl, obj);
            },
            uploadFile: function (eleId, postUrl, layUpload, beforeEleId, exts, done, error, accept) {
                upload(eleId, postUrl, layUpload, beforeEleId, exts, done, error, accept);
            },
            openFrame: function (url, title, width, height) {
                return openFrame(url, title, width, height);
            },
            setStatus: function (postUrl) {
                return setStatus(postUrl);
            },
            //排序
            sort: function (data) {
                return sort(data);
            },
            //查询
            search: function (data,type) {
                return search(data,type);
            },
            successReturn: function (data, index) {
                return successReturn(data, index);
            },
            errorReturn: function (data) {
                return errorReturn(data);
            },
            systemReturn: function (data) {
                return systemReturn(data);
            }
        }
    }();
</script>
